/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xiaopo.flying.stickerview.slice;

import com.xiaopo.flying.sticker.BitmapStickerIcon;
import com.xiaopo.flying.sticker.DeleteIconEvent;
import com.xiaopo.flying.sticker.DrawableSticker;
import com.xiaopo.flying.sticker.FlipHorizontallyEvent;
import com.xiaopo.flying.sticker.Sticker;
import com.xiaopo.flying.sticker.StickerView;
import com.xiaopo.flying.sticker.TextSticker;
import com.xiaopo.flying.sticker.ZoomIconEvent;
import com.xiaopo.flying.sticker.util.PixelMapFactoryUtil;
import com.xiaopo.flying.stickerview.HelloIconEvent;
import com.xiaopo.flying.stickerview.PhotoView;
import com.xiaopo.flying.stickerview.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;

import java.util.Arrays;

/**
 * MainAbilitySlice
 *
 * @since 2021-05-12
 */
public class MainAbilitySlice extends AbilitySlice {
    private static final int TEXTCOLOR = 0xFFFF0000;
    private static final int MAXTEXTSIZE = 14;
    private static final int OFFSETY = 200;
    private StickerView stickerView;
    private TextSticker sticker;
    private Image border;
    private PhotoView photoView;
    private ToastDialog toastDialog;

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initComponent();
        initData();
    }

    private void initComponent() {
        Component save = findComponentById(ResourceTable.Id_text_save);
        save.setClickedListener(this::save);
        Component reset = findComponentById(ResourceTable.Id_reset);
        reset.setClickedListener(this::reset);
        Component replace = findComponentById(ResourceTable.Id_replace);
        replace.setClickedListener(this::testReplace);
        Component remove = findComponentById(ResourceTable.Id_remove);
        remove.setClickedListener(this::testRemove);
        Component removeAll = findComponentById(ResourceTable.Id_remove_all);
        removeAll.setClickedListener(this::testRemoveAll);
        Component lock = findComponentById(ResourceTable.Id_lock);
        lock.setClickedListener(this::testLock);
        Component add = findComponentById(ResourceTable.Id_add);
        add.setClickedListener(this::testAdd);
        border = (Image) findComponentById(ResourceTable.Id_border);
        photoView = (PhotoView) findComponentById(ResourceTable.Id_photoview);
        photoView.setResPixelMap(ResourceTable.Media_haizewang_90);
        stickerView = (StickerView) findComponentById(ResourceTable.Id_sticker_view);
    }

    private void initData() {
        toastDialog = new ToastDialog(getContext());
        border.addDrawTask((component, canvas) -> {
            PixelMap pixelMap = ((Image) component).getPixelMap();
            PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();
            options.size = new Size(component.getWidth(), component.getHeight());
            ((Image) component).setPixelMap(PixelMap.create(pixelMap, options));
        });
        PixelMap deletePixelMap = PixelMapFactoryUtil.getPixelMapFromResource(getContext(),
            com.xiaopo.flying.sticker.ResourceTable.Media_sticker_ic_close_white_18dp,
            new ImageSource.DecodingOptions());
        BitmapStickerIcon deleteIcon = new BitmapStickerIcon(new PixelMapElement(deletePixelMap),
            BitmapStickerIcon.LEFT_TOP);
        deleteIcon.setIconEvent(new DeleteIconEvent());
        PixelMap zoomPixelMap = PixelMapFactoryUtil.getPixelMapFromResource(getContext(),
            com.xiaopo.flying.sticker.ResourceTable.Media_sticker_ic_scale_white_18dp,
            new ImageSource.DecodingOptions());
        BitmapStickerIcon zoomIcon = new BitmapStickerIcon(new PixelMapElement(zoomPixelMap),
            BitmapStickerIcon.RIGHT_BOTOM);
        zoomIcon.setIconEvent(new ZoomIconEvent());
        PixelMap flipPixelMap = PixelMapFactoryUtil.getPixelMapFromResource(getContext(),
            com.xiaopo.flying.sticker.ResourceTable.Media_sticker_ic_flip_white_18dp,
            new ImageSource.DecodingOptions());
        BitmapStickerIcon flipIcon = new BitmapStickerIcon(new PixelMapElement(flipPixelMap),
            BitmapStickerIcon.RIGHT_TOP);
        flipIcon.setIconEvent(new FlipHorizontallyEvent());
        PixelMap heartPixelMap = PixelMapFactoryUtil.getPixelMapFromResource(getContext(),
            ResourceTable.Media_ic_favorite_white_24dp, new ImageSource.DecodingOptions());
        BitmapStickerIcon heartIcon = new BitmapStickerIcon(new PixelMapElement(heartPixelMap),
            BitmapStickerIcon.LEFT_BOTTOM);
        heartIcon.setIconEvent(new HelloIconEvent());
        stickerView.setIcons(Arrays.asList(deleteIcon, zoomIcon, flipIcon, heartIcon));
        setStickerView();
        loadSticker();
    }

    private void setStickerView() {
        stickerView.setLocked(false);
        stickerView.setConstrained(true);
        stickerView.setOnStickerOperationListener(new StickerView.OnStickerOperationListener() {
            @Override
            public void onStickerAdded(Sticker msticker) {
            }

            @Override
            public void onStickerClicked(Sticker msticker) {
                if (msticker instanceof TextSticker) {
                    ((TextSticker) msticker).setTextColor(TEXTCOLOR);
                    stickerView.replace(msticker);
                    stickerView.invalidate();
                }
            }

            @Override
            public void onStickerDeleted(Sticker msticker) {
            }

            @Override
            public void onStickerDragFinished(Sticker msticker) {
            }

            @Override
            public void onStickerTouchedDown(Sticker msticker) {
            }

            @Override
            public void onStickerZoomFinished(Sticker msticker) {
            }

            @Override
            public void onStickerFlipped(Sticker msticker) {
            }

            @Override
            public void onStickerDoubleTapped(Sticker msticker) {
            }
        });
    }

    private void loadSticker() {
        sticker = new TextSticker(this);

        sticker.setDrawable(new ShapeElement(getContext(), com.xiaopo.flying.sticker.
            ResourceTable.Graphic_sticker_transparent_background));
        sticker.setText("Hello, world!");
        sticker.setTextColor(Color.BLACK.getValue());
        sticker.setTextAlign(LayoutAlignment.CENTER);
        sticker.resizeText();
        PixelMap pixelMap = PixelMapFactoryUtil.getPixelMapFromResource(getContext(),
            ResourceTable.Media_haizewang_215, new ImageSource.DecodingOptions());
        Element drawable = new PixelMapElement(pixelMap);

        PixelMap pixelMap1 = PixelMapFactoryUtil.getPixelMapFromResource(getContext(),
            ResourceTable.Media_haizewang_23, new ImageSource.DecodingOptions());
        Element drawable1 = new PixelMapElement(pixelMap1);

        stickerView.addSticker(new DrawableSticker(drawable));
        stickerView.addSticker(new DrawableSticker(drawable1), Sticker.Position.BOTTOM | Sticker.Position.RIGHT);

        PixelMap pixelMapBubble = PixelMapFactoryUtil.getPixelMapFromResource(getContext(),
            ResourceTable.Media_bubble, new ImageSource.DecodingOptions());
        Element bubble = new PixelMapElement(pixelMapBubble);
        stickerView.addSticker(
            new TextSticker(getApplicationContext())
                .setDrawable(bubble)
                .setText("Sticker" + System.lineSeparator())
                .setMaxTextSize(MAXTEXTSIZE)
                .resizeText(), Sticker.Position.TOP);
    }

    private void testReplace(Component component) {
        if (stickerView.replace(sticker)) {
            showDialog("Replace Sticker successfully!");
        } else {
            showDialog("Replace Sticker failed!");
        }
    }

    private void save(Component component) {
        stickerView.setPhotoView(photoView.getOrgPixelMap(), photoView.getRect(), photoView.getRectf());
        stickerView.save();
    }

    private void testLock(Component component) {
        stickerView.setLocked(!stickerView.isLocked());
    }

    private void testRemove(Component component) {
        if (stickerView.removeCurrentSticker()) {
            showDialog("Remove current Sticker successfully!");
        } else {
            showDialog("Remove current Sticker failed!");
        }
    }

    private void testRemoveAll(Component component) {
        stickerView.removeAllStickers();
    }

    private void reset(Component component) {
        stickerView.removeAllStickers();
        loadSticker();
    }

    private void testAdd(Component component) {
        stickerView.invalidate();
        final TextSticker msticker = new TextSticker(getApplicationContext());
        msticker.setText("Hello, world!");
        msticker.setTextColor(Color.BLUE.getValue());
        msticker.resizeText();
        stickerView.addSticker(msticker);
    }

    private void showDialog(String content) {
        DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(this)
            .parse(ResourceTable.Layout_layout_toast, null, false);
        Text textDialog = (Text) toastLayout.findComponentById(com.xiaopo.flying.sticker.ResourceTable.Id_msg_toast);
        textDialog.setMultipleLine(true);
        textDialog.setText(content);
        toastDialog.setContentCustomComponent(toastLayout)
            .setAlignment(LayoutAlignment.BOTTOM)
            .setOffset(0, OFFSETY)
            .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
            .show();
    }
}
